-- UIEnterDungeon
-- Create by zouyb
-- 地牢信息界面

require "game/ui/misc/UIIndicator"
require "game/ui/form/artifact/UIArtifactChoose"
require "game/ui/form/dungeon/UIRankingList"
require "game/ui/form/lictor/UILictorChoose"
require "game/ui/form/carriable_item/UICarriableItem"
require "game/ui/form/comment/UIComment"

-- UIDungeonInfo继承自Layer
UIEnterDungeon = class("UIEnterDungeon", function()
    return cc.Layer:create();
end);

function UIEnterDungeon.create(dungeonId)
    return UIEnterDungeon.new(dungeonId);
end

-- 构造函数
function UIEnterDungeon:ctor(dungeonId)
    self:setName("UIEnterDungeon");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/dungeon/EnterDungeon.csb");
    self:addChild(node);
    self.node = node;

    -- self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.dungeonId = dungeonId;

    self.itemCount = 0;

    self.lictorPets = {};

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘迷宫信息
    self:redrawDungeonInfo();

    -- 检查评论数量
    self:checkCommentCount();

    -- 神器图标显示
    local isShowArtifactt = self:isShowArtifactt()
    if isShowArtifactt == true then
        local shenqiImg = findChildByName(self.node, "CT/item1/item1");
        shenqiImg:setVisible(true);
        local  shenqiLock = findChildByName(self.node, "CT/item1/lock");
        shenqiLock:setVisible(false);

        -- 神器图标可点
        self:updateCarrayArtiHint();

        -- 选择神器
        local chooseBtn = findChildByName(node, "CT/item1");
        chooseBtn:addTouchEventListener(function (sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                -- 打开选择神器界面
                -- 进入地牢
                if UIMgr:getCurrentScene():isOpen("UIArtifactChoose") then
                    UIMgr:getCurrentScene():removeForm("UIArtifactChoose");
                end
                local uiArtifactChoose = UIArtifactChoose.create();
                UIMgr.getCurrentScene():addForm(uiArtifactChoose);
                AudioM.playFx("ui_open1");
            end
        end);

        -- 如果有可用神器跳动图标
        local hasAfactts = ItemM.getArtifact();
        local durability = 0;
        for _, classId in pairs(hasAfactts) do
            durability = ArtifactM.getDurability(classId)
            if durability > 0 then
               break;
            end
        end

        if #hasAfactts > 0 and durability > 0 then
            playBubbleAnima(shenqiImg, false, 0.75);
        end
    else
        local frameBg = findChildByName(self.node, "CT/item1");
        frameBg:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                alert(getLocStr(isShowArtifactt));
            end
        end);
    end

    -- 扈从1图标显示
    local isShowLictor1 = self:isShowLictor1();
    if isShowLictor1 == true then
        local lictorImg = findChildByName(self.node, "CT/item3/item3");
        lictorImg:setVisible(true);
        local  lictorLock = findChildByName(self.node, "CT/item3/lock");
        lictorLock:setVisible(false);

        -- 获取之前保存的扈从信息
        local lictorPets = ME.user.dbase:query("lictor_pets") or {};
        local petId = lictorPets[1];
        if LictorM.canDispatch(petId) then
            self.lictorPets["item3"] = petId;
            local pet = PetM.getMyPet(petId);
            local iconIndex = pet:getIcon();
            lictorImg:loadTexture(getHeroIconPath(iconIndex));


            -- 系别图标
            local departIcon = findChildByName(self.node, "CT/item3/depart_icon");

            local departOrder = PetM.query(petId, "department_order");
            local depart = departOrder[1];
            departIcon:loadTexture(getCareerDepartmentIconPath(depart));
            departIcon:setVisible(true);
        else
            -- 跳动图标
            local havePet = false;
            local pets = ME.user.pets;

            for petId, _ in pairs(pets) do
                if LictorM.canDispatch(petId, 3) and
                    self.lictorPets["item4"] ~= petId then
                    havePet = true;
                    break;
                end
            end

            if havePet ~= false then
                playBubbleAnima(lictorImg, false, 0.75);

                local hintNode = findChildByName(self.node, "CT/item3/hint");
                checkBlueBubbleStatus(hintNode, true, 0.8);
            end
        end

        -- 扈从1图标可点

        -- 选择扈从
        local chooseBtn = findChildByName(node, "CT/item3");
        chooseBtn:addTouchEventListener(function (sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                -- 打开选择扈从界面
                self:openLictorChoose(3);
                AudioM.playFx("ui_open1");
            end
        end);
    else
        local frameBg = findChildByName(self.node, "CT/item3");
        frameBg:addTouchEventListener(function (sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                alert(getLocStr(isShowLictor1));
            end
        end);
    end

    -- 扈从2图标显示
    local isShowLictor2 = self:isShowLictor2();
    if isShowLictor2 == true then
        local lictorImg = findChildByName(self.node, "CT/item4/item4");
        lictorImg:setVisible(true);
        local  lictorLock = findChildByName(self.node, "CT/item4/lock");
        lictorLock:setVisible(false);

        -- 获取之前保存的扈从信息
        local lictorPets = ME.user.dbase:query("lictor_pets") or {};
        local petId = lictorPets[2];
        if LictorM.canDispatch(petId) then
            self.lictorPets["item4"] = petId;
            local pet = PetM.getMyPet(petId);
            local iconIndex = pet:getIcon();
            lictorImg:loadTexture(getHeroIconPath(iconIndex));

                      -- 系别图标
            local departIcon = findChildByName(self.node, "CT/item4/depart_icon");

            local departOrder = PetM.query(petId, "department_order");
            local depart = departOrder[1];
            departIcon:loadTexture(getCareerDepartmentIconPath(depart));
            departIcon:setVisible(true);
        else
            -- 跳动图标
            local havePet = false;
            local pets = ME.user.pets;

            for petId, _ in pairs(pets) do
                if LictorM.canDispatch(petId, 4) and
                    self.lictorPets["item3"] ~= petId then
                    havePet = true;
                end
            end

            if havePet ~= false then
                playBubbleAnima(lictorImg, false, 0.75);
                local hintNode = findChildByName(self.node, "CT/item4/hint");
                checkBlueBubbleStatus(hintNode, true, 0.8);
            end
        end

        -- 扈从2图标可点

        -- 选择扈从
        local chooseBtn = findChildByName(node, "CT/item4");
        chooseBtn:addTouchEventListener(function (sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                -- 打开选择扈从界面
                self:openLictorChoose(4);
                AudioM.playFx("ui_open1");
            end
        end);
    else
        local frameBg = findChildByName(self.node, "CT/item4");
        frameBg:addTouchEventListener(function (sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                alert(getLocStr(isShowLictor2));
            end
        end);
    end

    -- 试剂图标显示
    local isShowReagent = self:isShowReagent();
    if isShowReagent == true then
        local shijiImg = findChildByName(self.node, "CT/item2/item2");
        shijiImg:setVisible(true);
        local  shijiLock = findChildByName(self.node, "CT/item2/lock");
        shijiLock:setVisible(false);

        -- 试剂图标可点

        -- 选择试剂
        local chooseBtn = findChildByName(node, "CT/item2");
        chooseBtn:addTouchEventListener(function (sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                -- 打开试剂选择界面
                -- 进入地牢
                if UIMgr:getCurrentScene():isOpen("UICarriableItem") then
                    UIMgr:getCurrentScene():removeForm("UICarriableItem");
                end
                local uiCarriableItem = UICarriableItem.create();
                UIMgr.getCurrentScene():addForm(uiCarriableItem);
                AudioM.playFx("ui_open1");
            end
        end);
        local hasCarriableItems = ItemM.getItemsByGroup(ME.user, 27);
        if #hasCarriableItems > 0 then
            playBubbleAnima(shijiImg, false, 0.75);
            local hintNode = findChildByName(self.node, "CT/item2/hint");
            checkBlueBubbleStatus(hintNode, true, 0.8);
        end
    else
        local item2 = findChildByName(self.node, "CT/item2");

        local function itemTouchClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
               alert(getLocStr(isShowReagent));
            end
        end
        item2:addTouchEventListener(itemTouchClick);
    end

    -- 适配
    self:resize();
end

-- 适配
function UIEnterDungeon:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIEnterDungeon:registerEventCallback()
    local node = self.node;
    -- 选择神器事件回调
    EventMgr.register("UIEnterDungeon", event.ARTIFACTT_CHOOSE_OK, function(classId)
        local artifactBg = findChildByName(node, "CT/item1");
        local shenqiImage = findChildByName(node, "CT/item1/item1");
        local hintNode = findChildByName(node, "CT/item1/hint");

        checkBlueBubbleStatus(hintNode, false);
        shenqiImage:setVisible(true);
        local function callFunc3()
            local iconIndex = ItemM.query(classId, "icon");
            shenqiImage:loadTexture(getItemIconPath(iconIndex));
            self.afClassId = classId;
            shenqiImage:stopAllActions();
        end
        playLictorEffect(artifactBg, classId, callFunc3);
    end);

    -- 试剂选择事件回调
    EventMgr.register("UIEnterDungeon", event.ITEM_CHOOSE_OK, function(args)
        local reagentBg = findChildByName(node, "CT/item2");
        local shijiImage = findChildByName(node, "CT/item2/item2");
        local hintNode = findChildByName(node, "CT/item2/hint");

        checkBlueBubbleStatus(hintNode, false);
        shijiImage:setVisible(true);
        local function callFunc2()
            local iconIndex = ItemM.query(args.classId, "icon");
            shijiImage:loadTexture(getItemIconPath(iconIndex));
            self.itemClassId = args.classId;
            self.itemCount = args.amount;
            shijiImage:stopAllActions();
        end
        playLictorEffect(reagentBg, args.classId, callFunc2);
    end);

    -- 选择扈从事件回调
    EventMgr.register("UIEnterDungeon", event.LICTOR_CHOOSE_OK, function(data)
        local lictorImage = findChildByName(self.node, "CT/item" .. data.itemId);
        local function callFunc()
            self:whenLictorChosen(data);
        end

        playLictorEffect(lictorImage, data.classId, callFunc, "pet");
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIEnterDungeon", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIEnterDungeon" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_TREE, TOPMENU_FRAME_LIFE);
        end
    end);

    -- 注册购买商品的事件回调
    EventMgr.register("UIEnterDungeon", event.BUY_GOODS, function(args)
        -- 提示玩家购买了商品
        local goodsId = args.goodsId;

        if MarketM.query(goodsId, "classify") ~= "hero" then
            alert(string.format(getLocStr("market_buy_succ"), MarketM.query(goodsId, "name")));
        end
    end);

    -- 关注评论数量更新
    EventMgr.register("UIEnterDungeon", event.UPDATE_COMMENT_COUNT, function(para)
        self:checkCommentCount(para);
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIEnterDungeon 界面析构清理");
            EventMgr.removeAll("UIEnterDungeon");

            local uiSubAreaList = UIMgr:getCurrentScene():getFormByName("UISubAreaList");
            local uiActivityDungeon = UIMgr.getCurrentScene():getFormByName("UIActivityDungeon");
            if uiSubAreaList ~= nil then
                uiSubAreaList:setVisible(true);
            elseif uiActivityDungeon ~= nil then
                uiActivityDungeon:setVisible(true);
            end
        elseif eventType == "enter" then
            local uiSubAreaList = UIMgr:getCurrentScene():getFormByName("UISubAreaList");
            local uiActivityDungeon = UIMgr.getCurrentScene():getFormByName("UIActivityDungeon");
            if uiSubAreaList ~= nil then
                uiSubAreaList:setVisible(false);
            elseif uiActivityDungeon ~= nil then
                uiActivityDungeon:setVisible(false);
            end
        end
    end);
end

-- 注册点击事件
function UIEnterDungeon:registerTouchEvent()
    local node = self.node;

    -- 地牢进入按钮
    local enterBtn = findChildByName(node, "CT/enter_btn");
    local function onEnterClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            if DungeonM.isInDungeon() then
                alert(getLocStr("cant_restart_dungeon"));

                return;
            end
            -- 删除可能遗留自动战斗的标示
            ME.user.dbase:deleteTemp("auto_start");

            -- 如果该地牢限制了出战的冈布奥，那么检测一下
            local limitPet = DungeonAreaM.query(self.dungeonId, "limit_active_pet");

            if type(limitPet) == "number" and limitPet ~= ME.user.dbase:query("active_pet", 0) then
                -- "限XXX冈布奥出战"
                alert(string.format(getLocStr("dungeon_limit_active_pet"), PetM.query(limitPet, "name")));
                return;
            end

            -- 如果体力不足
            local requireLife = DungeonAreaM.calcDungeonLifeCost(self.dungeonId);
            if ME.user.dbase:query("life", 0) < requireLife  then
                -- 弹出购买体力提示
                confirmBuyLife();
            else
                local function onCheckExtraPackDone()
                    local function enterDungeon()
                        local afClassId = self.afClassId;
                        local itemClassId = self.itemClassId;
                        local itemCount = self.itemCount;
                        local lictorPets = self.lictorPets;
                        local dungeonId = self.dungeonId;

                        local function callback()
                            -- 显示通信中界面
                            showCommunicatingForm(nil, true, false, nil, "enter_dungeon", true);

                            local extra = {};

                            -- 神器
                            if ArtifactM.carryArtifact(afClassId) then
                                extra["artifact_id"] = afClassId;
                            end

                            -- 试剂
                            if 0 ~= itemCount and ItemM.carryDungeonItem(itemClassId, 1) then
                                -- 只能携带一个
                                extra["carry_item"] = itemClassId;
                            end

                            -- 灵魂链接
                            if LictorM.dispatchLictor(lictorPets, dungeonId) then
                                extra["lictors"] = lictorPets;
                            end

                            DungeonServiceM.startEnterService(dungeonId, extra);

                        end
                        playLifeConsumeEffect(requireLife, callback);
                    end

                    local noTask = true;
                    for _, taskInfo in ipairs(DailyTaskM.getTaskList()) do
                        if type(taskInfo.camp_id) == "number" then
                            if taskInfo.dungeon_id == self.dungeonId and taskInfo.is_finish == 0 then
                                if CampM.getPetCamp(ME.user.dbase:query("active_pet", 0)) ~= taskInfo.camp_id then
                                    noTask = false;
                                    local msg = string.format(getLocStr("daily_task_notice8"), DailyTaskM.query(taskInfo.id, "desc_arg"), CampM.query(taskInfo.camp_id, "name"));
                                    local title = getLocStr("circus_title");

                                    local function callback()
                                        -- 进入迷宫
                                        enterDungeon();
                                    end

                                    -- 弹出消耗确认提示框
                                    AudioM.playFx("button_spell");
                                    confirm2(CONFIRM_TYPE_OK_CANCEL, title, msg, callback,
                                        nil, getLocStr("btn_text_no_care"));
                                end
                            end
                        end
                    end

                    -- 没有任务的话直接进地牢
                    if noTask then
                        enterDungeon();
                    end
                end

                -- 检查是否下载独立资源包
                checkExtraPackDownload(onCheckExtraPackDone);
            end
        end
    end
    AddTouchEventListener(enterBtn, onEnterClick);
    enterBtn:setTitleText("");
    local enterLabel = findChildByName(enterBtn, "enter_label");
    TextStyleM.setTextStyle(enterLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -4, nil, nil, nil, nil, true);
    enterLabel:setString(getLocStr("enter_dungeon_1"));

    local areaName = "";
    local commentId = self.dungeonId;

    if ActivityDungeonM.isActivityDungeon(self.dungeonId) then
        -- 活动副本TODO
    elseif SkyInstanceM.isSkyInstance(self.dungeonId) then
        -- 天空副本TODO
    else
        local parentId = DungeonAreaM.query(self.dungeonId, "parent_id");
        if parentId ~= 0 then
            commentId = parentId;
        end
    end
    -- 名称
    areaName = DungeonAreaM.query(commentId, "name");

    -- 评论界面参数
    local heroConfig = PetM.query(self.classId);
    local data = {
        ["title"] = areaName,
        ["type"] = "dungeon_" .. tostring(commentId),
    }

    -- 注册评论按钮
    local btnComment = findChildByName(self.node, "BT/btn_comment");
    local function onCommentClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            UIMgr.getCurrentScene():removeFormByName("UIComment");
            local uiComment = UIComment.create(data);
            UIMgr.getCurrentScene():addForm(uiComment);
        end
    end
    btnComment:addTouchEventListener(onCommentClick);
    TextStyleM.setTextStyle(btnComment, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnComment:setTitleText(getLocStr("btn_text_new_comment"));

    -- 获取评论数量
    Operation.cmd_get_comment_counts(data.type);

    -- TODO活动/天空副本暂时不显示
    if ActivityDungeonM.isActivityDungeon(self.dungeonId) or
        SkyInstanceM.isSkyInstance(self.dungeonId) then
        btnComment:setVisible(false);
    end

    -- 返回按钮
    local btnBack = findChildByName(node, "BT/close_btn");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIEnterDungeon");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 提示
    local activityTip = findChildByName(self.node, "CT/activity_tip");
    local function onTipClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local activityCfg = ActivityDungeonM.getActivityByDungeonId(self.dungeonId);
            if activityCfg["grade"] ~= ACTIVITY_GRADE_DIFFICULT
                or not activityCfg["tip"] or #activityCfg["tip"] <= 0 then
                return;
            end

            -- 困难提示
            local content = getLocStr("activity_tip_pre") .. activityCfg["tip"];
            showActivityTip(activityCfg["name"], content);

            AudioM.playFx("button_click");
        end
    end
    activityTip:addTouchEventListener(onTipClick);
end

-- 重绘迷宫信息
function UIEnterDungeon:redrawDungeonInfo()
    local node = self.node;

    -- 体力
    local enterBtn = findChildByName(node, "CT/enter_btn");
    local lifeIcon = findChildByName(enterBtn, "life_icon");
    local lifeCost = DungeonAreaM.calcDungeonLifeCost(self.dungeonId);
    local lifeLayer = createLifeLayer(lifeCost, "center", -0.4);
    lifeIcon:addChild(lifeLayer);
    lifeIcon:setVisible(true);

    -- 区域标题
    local caption = findChildByName(node, "CT/caption");
    local areaName = "";

    -- 活动提示节点
    local activityTip = findChildByName(node, "CT/activity_tip");
    activityTip:setVisible(false);

    -- 如果是活动迷宫，显示活动名称
    if ActivityDungeonM.isActivityDungeon(self.dungeonId) then
        local activityCfg = ActivityDungeonM.getActivityByDungeonId(self.dungeonId);
        areaName = activityCfg["name"];
        if activityCfg["grade"] == ACTIVITY_GRADE_DIFFICULT
            and activityCfg["tip"] and #activityCfg["tip"] > 0 then
            -- 困难模式给提示气泡
            activityTip:setVisible(true);
            activityTip:setScale(0.64);
            activityTip:setPosition(cc.p(245, 270));
            playBubbleAnima(activityTip, false, 0.64);
        end
    else
        local parentId = DungeonAreaM.query(self.dungeonId, "parent_id");
        if parentId ~= 0 then
            areaName = DungeonAreaM.query(parentId, "name");
        else
            areaName = DungeonAreaM.query(self.dungeonId, "name");
        end
    end
    caption:setString(areaName);
    TextStyleM.setTitleStyle(caption);

    local maxFloor = DungeonAreaM.query(self.dungeonId, "max_floor");
    local maxScoreLabel = findChildByName(node, "CT/max_score");
    TextStyleM.setSubheadStyle(maxScoreLabel);
    maxScoreLabel:setVisible(true);

    if ActivityDungeonM.isActivityDungeon(self.dungeonId) then
        -- 如果是活动迷宫，显示难度
        local activity = ActivityDungeonM.getActivityByDungeonId(self.dungeonId);
        if activity == nil then
            error(string.format("获取不到迷宫(%d)的活动配置", self.dungeonId));
        end

        local str = ""
        if ActivityM.query(activity["id"], "rule") == "sky_activity" then
            local petId = activity["pet_id"];
            str = PetM.query(petId, "short_name");
        else
            local grade = activity["grade"];
            if grade == ACTIVITY_GRADE_EASY then
                str = getLocStr("activity_grade_easy");
            elseif grade == ACTIVITY_GRADE_NORMAL then
                str = getLocStr("activity_grade_normal");
            else
                str = getLocStr("activity_grade_difficult");
            end
        end
        maxScoreLabel:setString(str);
    else
        if maxFloor == 0 then
            -- 无尽模式
            maxScoreLabel:setString(getLocStr("endless_dungeon"));
        else
            if "sky_instance" == DungeonAreaM.query(self.dungeonId, "type") then
                -- "天空副本"
                maxScoreLabel:setString(getLocStr("sky_instance"));
            elseif AwakeM.isAwakeDungeon(self.dungeonId) then
                -- "限XXX冈布奥出战"
                local limitPet = DungeonAreaM.query(self.dungeonId, "limit_active_pet");
                maxScoreLabel:setString(string.format(getLocStr("dungeon_limit_active_pet"), PetM.query(limitPet, "name")));
            else
                maxScoreLabel:setString(DungeonAreaM.query(self.dungeonId, "name"));
            end
        end
    end

    -- 区域说明
    local desc = findChildByName(node, "CT/desc");
    TextStyleM.setTextStyle(desc, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, getLocKerning(), nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
    desc:setString(DungeonAreaM.query(self.dungeonId, "desc"));

    -- 最高层
    local dungeonInfo = ME.user.dbase:query("dungeon_progress", {});
    local curDungeonInfo = dungeonInfo[self.dungeonId];
    local layerAmount = 0;
    if curDungeonInfo ~= nil then
        layerAmount = curDungeonInfo["max"] or 0;
    end

    local maxLayer = findChildByName(self.node,"CT/max_layer");
    if ActivityDungeonM.isActivityDungeon(self.dungeonId) then
        -- 活动迷宫不显示这个
        maxLayer:setVisible(false);
    elseif layerAmount > 0 then
        maxLayer:setVisible(true);
        local maxLabel = findChildByName(maxLayer, "max_label");
        TextStyleM.setTextStyle(maxLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE, true, -5);
        maxLabel:setString(getLocStr("arrive_max_layer"));

        local maxNum = findChildByName(maxLayer, "max_num");
        TextStyleM.setTextStyle(maxNum, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_LIGHT_YELLOW, true, -5);
        maxNum:setString(layerAmount.." F");
    end

    -- 上次死亡
    local legacyNode = findChildByName(node, "BT/legacy");
    local dungeonLegacy = ME.user.dbase:query("dungeon_legacy", {});
    local legacyInfo = dungeonLegacy[self.dungeonId];
    local btnComment = findChildByName(self.node, "BT/btn_comment");

    if not legacyInfo or table.keys(legacyInfo)[1] == 0 or
        AwakeM.isAwakeDungeon(self.dungeonId) then
        -- 没有遗产信息，不显示
        legacyNode:setVisible(false);
        -- 需要把评论按钮置左
        btnComment:setPositionX(legacyNode:getPositionX());
    else
        local legacyLabel = findChildByName(legacyNode, "legacy_label");
        TextStyleM.setTextStyle(legacyLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BEIGE, true, -5);
        legacyLabel:setString(table.keys(legacyInfo)[1] .. " F");
    end
end

-- 神器选项是否显示
function UIEnterDungeon:isShowArtifactt()
    if AwakeM.isAwakeDungeon(self.dungeonId) then
        return "dungeon_not_support";
    end

    -- 玩家拥有的神器
    local hasArtifacts = ItemM.getArtifact();

    -- 拥有神器才开放该功能
    if #hasArtifacts < 1 then
        return "no_aritfact_scrap";
    end

    return true;
end

-- 提示有神器可携带
function UIEnterDungeon:updateCarrayArtiHint()
    -- 是否有可用神器
    local hasArtifacts = ItemM.getArtifact();
    local isOk = false;
    -- 判断玩家身上是否有可用神器
    for _, artifactId in pairs(hasArtifacts) do
        local  durability = ArtifactM.getDurability(artifactId) or 0; -- 剩余耐久度
        if durability > 0 then
            isOk = true;
        end
    end

    --
    local hintNode = findChildByName(self.node, "CT/item1/hint");
    checkBlueBubbleStatus(hintNode, isOk, 0.8);
end

-- 扈从1选项是否显示
function UIEnterDungeon:isShowLictor1()
    if AwakeM.isAwakeDungeon(self.dungeonId) then
        return "dungeon_not_support";
    end

    if not FeatureItemM.isFeatureOpen("soulstone1") then
        return "get_soulstone1_to_unlock"
    end

    if LictorM.lictorLimit() <= 0 then
        alert(getLocStr("activate_soulstone1_to_unlock"));
    end

    return true;
end

-- 扈从2选项是否显示
function UIEnterDungeon:isShowLictor2()
    if AwakeM.isAwakeDungeon(self.dungeonId) then
        return "dungeon_not_support";
    end

    if not FeatureItemM.isFeatureOpen("soulstone2") then
        return "get_soulstone2_to_unlock";
    end

    if LictorM.lictorLimit() < 2 then
        return "activate_soulstone2_to_unlock";
    end

    return true;
end

-- 试剂选项是否显示
function UIEnterDungeon:isShowReagent()
    if AwakeM.isAwakeDungeon(self.dungeonId) then
        return "dungeon_not_support";
    end

    if not FeatureItemM.isFeatureOpen("reagent") then
        return "is_closed";
    end

    if AlchemyWorkshopM.getStrengthenLevel(18) <= 0 then
        return "not_active_reagent";
    end

    return true;
end

-- 打开排行榜
function UIEnterDungeon:openRankingList()
    local function callback()
        if UIMgr:getCurrentScene():isOpen("UIRankingList") then
            UIMgr:getCurrentScene():removeFormByName("UIRankingList");
        end

        local uiRankingList = UIRankingList.create(self.dungeonId);
        UIMgr.getCurrentScene():addForm(uiRankingList);
    end
    checkIfGuestNeedBind(callback);
end

-- 打开选择扈从界面
function UIEnterDungeon:openLictorChoose(itemId)

    if UIMgr:getCurrentScene():isOpen("UILictorChoose") then
        UIMgr:getCurrentScene():removeForm("UILictorChoose");
    end

    local uiLictorChoose = UILictorChoose.create(ME.user.dbase:query("active_pet"), itemId, self.lictorPets);
    UIMgr.getCurrentScene():addForm(uiLictorChoose);
end

-- 选择了扈从之后的回调
function UIEnterDungeon:whenLictorChosen(data)
    local lictorImage = findChildByName(self.node, "CT/item"..data.itemId.."/item"..data.itemId);
    lictorImage:setVisible(true);
    local pet = PetM.getMyPet(data.classId);
    local iconIndex = pet:getIcon();
    lictorImage:loadTexture(getHeroIconPath(iconIndex));

    -- 系别图标
    local departIcon = findChildByName(self.node, "CT/item".. data.itemId .. "/depart_icon");

    local departOrder = PetM.query(data.classId, "department_order");
    local depart = departOrder[1];
    departIcon:loadTexture(getCareerDepartmentIconPath(depart));
    departIcon:setVisible(true);

    -- 如果此次选择的扈从跟之前选择的一样，那么之前的那个要干掉
    if data.itemId == 3 and self.lictorPets["item4"] == data.classId then
        self.lictorPets["item4"] = nil;
        local lictorImage = findChildByName(self.node, "CT/item4/item4");
        lictorImage:loadTexture("images/ui/artifactt/artifactt_repair/brain.png");
    elseif data.itemId == 4 and self.lictorPets["item3"] == data.classId then
        self.lictorPets["item3"] = nil;
        local lictorImage = findChildByName(self.node, "CT/item3/item3");
        lictorImage:loadTexture("images/ui/artifactt/artifactt_repair/heart.png");
    end

    self.lictorPets["item"..data.itemId] = data.classId;

    -- 跳动图标
    local lictorImage1 = findChildByName(self.node, "CT/item3/item3");
    local lictorImage2 = findChildByName(self.node, "CT/item4/item4");

    -- 蓝色的泡泡
    local hintNode3 = findChildByName(self.node, "CT/item3/hint");
    local hintNode4 = findChildByName(self.node, "CT/item4/hint");

    -- 先都关闭跳动
    lictorImage1:stopAllActions();
    lictorImage2:stopAllActions();

    checkBlueBubbleStatus(hintNode3, false);
    checkBlueBubbleStatus(hintNode4, false);

    -- 遍历所有宝宝，判断是否有符合条件的
    local havePet1 = false;
    local havePet2 = false;
    local pets = ME.user.pets;

    for petId, _ in pairs(pets) do
        if LictorM.canDispatch(petId, 3) and
            self.lictorPets["item4"] ~= petId then
            havePet1 = true;
        end
        if LictorM.canDispatch(petId, 4) and
            self.lictorPets["item3"] ~= petId then
            havePet2 = true;
        end
    end

    -- 开启item3的跳动
    if havePet1 and not self.lictorPets["item3"] then
         if self:isShowLictor1() == true then
             playBubbleAnima(lictorImage1, false, 0.75);
             checkBlueBubbleStatus(hintNode3, true, 0.8);
        end
    end

    -- 开启item4的跳动
    if havePet2 and not self.lictorPets["item4"] then
        if self:isShowLictor2() == true then
           playBubbleAnima(lictorImage2, false, 0.75);
           checkBlueBubbleStatus(hintNode4, true, 0.8);
        end
    end
end

-- 检查评论数量
function UIEnterDungeon:checkCommentCount(para)
    -- 评论按钮
    local btnComment = findChildByName(self.node, "BT/btn_comment");
    local commentLabel = findChildByName(btnComment, "comment_label");
    local hintNode = findChildByName(btnComment, "hint");
    local commentId = self.dungeonId;

    -- 如果是活动迷宫，显示活动名称
    if ActivityDungeonM.isActivityDungeon(self.dungeonId) then
        -- 活动副本TODO
    elseif SkyInstanceM.isSkyInstance(self.dungeonId) then
        -- 天空副本TODO
    else
        -- 主线副本
        local parentId = DungeonAreaM.query(self.dungeonId, "parent_id");
        if parentId ~= 0 then
            commentId = parentId;
            -- 不是主线副本不显示
            btnComment:setVisible(false);
        end
    end

    local commentType = "dungeon_" .. tostring(commentId);
    if para and para.commentType ~= commentType then
        return;
    end

    local count = CommentM.getCommentCount(commentType);
    btnComment:setTitleText("");
    local kerning = 0;
    if getLang() == "zh" or getLang == "tw" then
        kerning = 4;
    end
    TextStyleM.setTextStyle(commentLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning, nil, nil, nil, nil, true);
    commentLabel:setString(string.format(getLocStr("btn_text_comment_num"), count));
end
